  /*!
   * jQuery lightweight plugin boilerplate
   * Original author: @ajpiano
   * Further changes, comments: @addyosmani
   * Licensed under the MIT license
   */

// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
(function ( $, window, document, undefined ) {

    // undefined is used here as the undefined global
    // variable in ECMAScript 3 and is mutable (i.e. it can
    // be changed by someone else). undefined isn't really
    // being passed in so we can ensure that its value is
    // truly undefined. In ES5, undefined can no longer be
    // modified.

    // window and document are passed through as local
    // variables rather than as globals, because this (slightly)
    // quickens the resolution process and can be more
    // efficiently minified (especially when both are
    // regularly referenced in your plugin).

    // Create the defaults once
    var pluginName = 'c_slideshow',
      defaults = {
        'bullet'         : false,
        'autorotate'     : false,
        'resize'         : false,
        'imgHeight'      : 900,
        'lightSwitch'    : false,
        'duration'       : 6500,
        'numberOfSlides' : false,
        'swipe'          : true
      };

    // The actual plugin constructor
    function Plugin( element, options ) {
      this.element = element;

      // jQuery has an extend method that merges the
      // contents of two or more objects, storing the
      // result in the first object. The first object
      // is generally empty because we don't want to alter
      // the default options for future instances of the plugin
      this.options = $.extend( {}, defaults, options) ;

      this._defaults = defaults;
      this._name = pluginName;

      this.init();
    }

    Plugin.prototype = {

      init: function() {
        // Place initialization logic here
        // You already have access to the DOM element and
        // the options via the instance, e.g. this.element
        // and this.options
        // you can add more functions like the one below and
        // call them like so: this.yourOtherFunction(this.element, this.options).

        this.lastSlide = $('ul:first > li', this.element).length - 1;
        this.currentSlide = 0;
        this.arrayOfSlides = [];

        if (this.lastSlide > 0) {

          var that = this;

          // Move every slide down except the first one
          $('ul:first > li:gt(0)', this.element).css( {'z-index': 1, 'visibility': 'hidden'} );
          // Move current slide above the others
          $('ul:first > li:eq(0)', this.element).css( {'z-index': 2, 'visibility': 'visible'} );
          // Create right and left navigation
          $(this.element)
            .prepend('<a href="#" class="sl-control sl-previous">Prev</a>')
            .append('<a href="#" class="sl-control sl-next">Next</a>');

          // Create thumbnail
          if (this.options.bullet) {
            $(this.element).append('<div class="sl-thumbs"></div>');
            // Create a button for each slide
            for (var i=0; i <= this.lastSlide; i += 1) {
              $('.sl-thumbs', this.element).append('<a href="#' +'" class="sl-control">' + (i+1) + '</a>');
            }
            // Add active class to the first button
            $('.sl-thumbs a:eq(0)', this.element).addClass('active');
          }

          // Auto-rotate.
          if (this.options.autorotate) {
            this.timeout = setTimeout( function () {that._autoRotate(); }, this.options.duration );
          }

          // Theme switch.
          if (this.options.lightSwitch) {
            this._toggleTheme(this.currentSlide);
          }

          $('.sl-previous', this.element).click( function () {
            if (that.currentSlide > 0) {
              that.slide( that.currentSlide-1, 1 );
            } else {
              that.slide( that.lastSlide, 1 );
            }
            return false;
          });

          $('.sl-next', this.element).click( function () {
            if (that.currentSlide < that.lastSlide) {
              that.slide( that.currentSlide+1, -1 );
            } else {
              that.slide( 0, -1 );
            }
            return false;
          });

          // Add swipe event on slideshow.
          if (this.options.swipe) {
            $(this.element).swipeEvents().bind("swipeLeft",  function(){
              if (that.currentSlide < that.lastSlide) {
                that.slide( that.currentSlide+1, -1 );
              } else {
                that.slide( 0, -1 );
              }
            });

            $(this.element).bind("swipeRight",  function(){
              if (that.currentSlide > 0) {
                that.slide( that.currentSlide-1, 1 );
              } else {
                that.slide( that.lastSlide, 1 );
              }
            });
          }

          // Action when a button is clicked
          $('.sl-thumbs a', this.element).click( function () {
            // slide to the left or right?
            var direction = $(this).index() > that.currentSlide ? -1 : 1 ;
            that.slide( $(this).index(), direction );
            return false;
          });

          $('.gallery .sl-control').click( function () {
            // slide to the left or right?
            var direction = $(this).parent().index() > that.currentSlide ? -1 : 1 ;
            that.slide( $(this).parent().index(), direction );
            return false;
          });

        }

        // Special case for the homepage slideshows
        if (this.options.resize) {

          var that = this;

          // Move slideshow under the header
          $('body').addClass('homepage');

          // Display specific slide on page load
          if(window.location.hash) {
            var hash = window.location.hash.substring(1); // Put hash in variable, remove the # character
            // Test if hash is a number (http://stackoverflow.com/a/1830844) and an existing slide
            if ( !isNaN(parseFloat(hash)) && isFinite(hash) && hash <= that.lastSlide ) {
              var direction = hash > that.currentSlide ? -1 : 1 ;
              that.slide( hash-1, direction );
            }
          }

          // Apply on load and resize events
          $(window).load(function(){
            that._resizeSlideshow();
          });
          $(window).resize(function() {
            that._resizeSlideshow();
          });
        }

        if (this.options.numberOfSlides) {

          this._putSlidesInArray();

          $(this.element)
            .find('.sl-previous')
            .wrap('<div class="sl-control-container" id="sl-previous-container" />');
          $("#sl-previous-container").append('<div class="info-number-slide info-number-slide-previous"></div>');

          $(this.element)
            .find('.sl-next')
            .wrap('<div class="sl-control-container" id="sl-next-container" />');

          $("#sl-next-container").append('<div class="info-number-slide info-number-slide-next"></div>');

          $("#sl-previous-container .info-number-slide-previous").text(this._countPrevious(this.arrayOfSlides, (this.currentSlide + 1))+'/'+(this.lastSlide + 1));
          $("#sl-next-container .info-number-slide-next").text(this._countNext(this.arrayOfSlides, (this.currentSlide + 1))+'/'+(this.lastSlide + 1));

          $('.sl-previous', this.element).mouseenter( function () {
            $('.info-number-slide-previous').stop(true, true).fadeIn();
          }).mouseleave(function () {
            $('.info-number-slide-previous').fadeOut();
          });

          $('.sl-next', this.element).mouseenter( function () {
            $('.info-number-slide-next').stop(true, true).fadeIn();
          }).mouseleave(function () {
            $('.info-number-slide-next').fadeOut();
          });
        }

      },

      _putSlidesInArray: function () {
        for (var i = 1; i <= (this.lastSlide + 1); i++) {
          this.arrayOfSlides.push(i);
        }
      },

      _countNext: function (p, start) {
        return p[($.inArray(start, p) + 1) % p.length];
      },

      _countPrevious: function (p, start) {
        return p[($.inArray(start, p) - 1 + p.length) % p.length];
      },

      _autoRotate: function () {
        if (this.currentSlide < this.lastSlide) {
          this.slide( this.currentSlide+1, -1 );
        } else {
          this.slide( 0, -1 );
        }
      },

      _toggleTheme: function (current) {
        if ($('ul:first > li:eq('+current+')', this.element).hasClass('light')) {
          $('body').addClass('light bridal');
        } else {
          $('body').removeClass('light bridal');
        }
      },

      // Recalculate the image dimensions when the browser window is resized
      _resizeSlideshow: function () {

        var that = this;

        // Determine maximum slide height
        var maxSlideHeight = $(window).height() -30,
          image = $('.sl-image', this.element),
          videoIndex,
          minHeight,
          videoMargin,
          pageWidth = $("#page").width();

        // Moving the arrows from slideshow at the left and right of the page
        $('.sl-next', this.element).css("right",- ((pageWidth - 980) / 2) + "px");
        $('.sl-previous', this.element).css("left",- ((pageWidth - 980) / 2) + "px");

        if ( maxSlideHeight < this.options.imgHeight ) { // If height is less than the real image size
          image.css('height', maxSlideHeight);
          if ( image.width() < $(window).width() ) { // The image must not be narrower than the window
            minHeight = $(window).width() < 1600 ? $(window).width() / 1.7777777 : 900 ; // 1600/900 ratio
            image.css('height', minHeight);
          }
          if ( image.width() < 980 ) { // The image must not be narrower than the main column
            image.css('height', 565);
          }
        } else { // If the window is higher than the real image height. 900 = original image's height
          image.css('height', this.options.imgHeight);
        }

        $(".video-wrapper-auto").each(function(){
          videoIndex = $(this).parents("li").data('playerId');
          jwplayer(videoIndex).resize( image.width(), image.height() );
          videoMargin = (1600 - image.width()) / 2;
          $(".video-wrapper-auto > div").css('margin-left', videoMargin); // Center the video
        });

        // Resize the containers to the same size as the images
        $('.hp-slideshow').css('height', image.height());
        $('.hp-slideshow ul:first > li').css( {'height': image.height()} );
        $('.hp-slideshow ul:first').css( {'height': image.height()} );

        // Move thumbnails above the fold
        if ( $(window).height() < minHeight && $(window).height() > 550 ) {
          $('.sl-thumbs', this.element).css( {'top': maxSlideHeight + "px"} );
        } else {
          $('.sl-thumbs', this.element).css( {'top': image.height() -30 + "px"} );
        }

      },

      slide: function (newSlide, direction) {

        var that = this;

        if ( newSlide !== this.currentSlide && !$(':animated', this.element).length ) { // No action if same slide or already running
          // Plays video when displayed, pauses when hidden
          var newVideo = $('ul > li:eq('+newSlide+')', that.element).data('playerId'),
              currentVideo = $('ul > li:eq('+this.currentSlide+')', that.element).data('playerId'),
              slideWidth = $('.sl-image:eq(0)', that.element).width();

          if ( newVideo ) { // Rewind and play the video
            jwplayer(currentVideo).seek(0);
            jwplayer(newVideo).pause(false);
          }

          $('.sl-thumbs a:eq(' +this.currentSlide+ ')', this.element).removeClass('active');
          // Move current and next slides
          $('ul:first > li:eq('+newSlide+')', this.element)
            .css( {'left': (direction * -slideWidth), 'z-index': '2', 'visibility': 'visible'} )
            .animate( {'left': 0 }, 1000, 'swing');
          $(this.element).trigger({
            'type': "slideOver",
            'current': this.currentSlide,
            'newSlide': newSlide,
            'nb': this.lastSlide
          });
          if (this.options.lightSwitch) {
            this._toggleTheme(newSlide);
          }
          $('ul:first > li:eq('+this.currentSlide+')', this.element)
            .css( {'left': 0, 'z-index': '2', 'visibility': 'visible'} )
            .animate( {'left': direction * slideWidth}, 1000, 'swing',
            function() { // Reset old slide when animation ends ('complete' callback)
              clearTimeout(that.timeout); // Clear the autoRotation then set new duration
              $('ul:first > li:eq('+that.currentSlide+')', that.element).css( {'left': 0, 'z-index': '1', 'visibility': 'hidden'} );
              $('.sl-thumbs a:eq(' +newSlide+ ')', that.element).addClass('active');
              if ( newVideo && that.options.autorotate) { // Get video length in seconds
                var getTime = function() {
                  var video_time = (jwplayer(currentVideo).getDuration()*1000) - 2000;
                  that.timeout = setTimeout( function () {that._autoRotate(); }, video_time );
                };
                setTimeout( getTime, 2000);
              } else {
                if (that.options.autorotate) {
                  that.timeout = setTimeout( function () {that._autoRotate(); }, that.options.duration );
                }
              }
              if ( currentVideo ) { // Stop the video once it's hidden
                jwplayer(currentVideo).pause(true);
              }
              that.currentSlide = newSlide;
              if (that.options.numberOfSlides) {
                $("#sl-previous-container .info-number-slide-previous").text(that._countPrevious(that.arrayOfSlides, (that.currentSlide + 1))+'/'+(that.lastSlide + 1));
                $("#sl-next-container .info-number-slide-next").text(that._countNext(that.arrayOfSlides, (that.currentSlide + 1))+'/'+(that.lastSlide + 1));
              }
            }
          );
        }
      }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function ( options ) {
      var args = arguments;
      if (options === undefined || typeof options === 'object') {
        return this.each(function () {
          if (!$.data(this, 'plugin_' + pluginName)) {
            $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
          }
        });
      } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
        return this.each(function () {
          var instance = $.data(this, 'plugin_' + pluginName);
          if (instance instanceof Plugin && typeof instance[options] === 'function') {
            instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
          }
        });
      }
    };

})( jQuery, window, document );

(function($) { 
  $.fn.swipeEvents = function() {
    return this.each(function() {
      
      var startX,
          startY,
          $this = $(this);
      
      $this.bind('touchstart', touchstart);
      
      function touchstart(event) {
        var touches = event.originalEvent.touches;
        if (touches && touches.length) {
          startX = touches[0].pageX;
          startY = touches[0].pageY;
          $this.bind('touchmove', touchmove);
        }
      }
      
      function touchmove(event) {
        var touches = event.originalEvent.touches;
        if (touches && touches.length) {
          var deltaX = startX - touches[0].pageX;
          var deltaY = startY - touches[0].pageY;
          
          if (deltaX >= 50) {
            $this.trigger("swipeLeft");
            event.preventDefault();
          }
          if (deltaX <= -50) {
            $this.trigger("swipeRight");
            event.preventDefault();
          }
        }
      }
      
    });
  };
})(jQuery);

$(function(){
	/* 幻灯片切换 Begin */
	$('.hp-slideshow').c_slideshow({'bullet': true, 'autorotate': true, 'resize': true, 'lightSwitch': true, 'swipe': true});
	/* 幻灯片切换 End */
	
	/* 二级导航展示 Begin */
	$('#secondary .trigger-link-megamenu').mouseenter(function(){
		$("select").blur(); // To close any opened select that may display over the menu
		var $this = $(this);
		$('.wrapper-megam').delay(100).fadeOut('slow');
		$(this).find('.wrapper-megam').stop(true, true).fadeIn('fast');
	});
	
	$('#secondary .trigger-link-megamenu').mouseleave(function(){
		$(this).find('.wrapper-megam').stop(true, true)
								  .delay(100)
								  .fadeOut('fast', function(){
									$(this).attr('style', '');
								  });
	});
	/* 二级导航展示 End */
});